package socket;

import message.BaseMessage;
import message.TestMessage;
import thread.ClientThread;
import view.LoginDialog;
import view.OnlineRoom;
import view.RoomList;

import javax.swing.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 客户端.
 *
 * @author 张天羿
 */
public class ChessClient {
    private static ChessClient instance;

    private ChessClient() {
    }

    public static ChessClient getInstance() {
        if (instance == null) {
            instance = new ChessClient();
        }
        return instance;
    }

    private String host = "localhost";
    private int port = 8008;
    private Socket socket;
    private ClientThread clientThread = null;
    private boolean connected = false;
    private OnlineRoom room;
    private LoginDialog loginDialog;
    private RoomList roomList;


    public Socket getSocket() {
        return socket;
    }

    public OnlineRoom getRoom() {
        return room;
    }

    public void setRoom(OnlineRoom room) {
        this.room = room;
    }

    public LoginDialog getLoginDialog() {
        return loginDialog;
    }

    public void setLoginDialog(LoginDialog loginDialog) {
        this.loginDialog = loginDialog;
    }

    public RoomList getRoomList() {
        return roomList;
    }

    public void setRoomList(RoomList roomList) {
        this.roomList = roomList;
    }

    public boolean isConnected() {
        return connected;
    }

    /**
     * 新建客户端,并尝试连接,成功则生成客户端线程不断监听.
     *
     * @return 连接是否成功
     * @see ClientThread
     */
    public boolean connect() {
        while (this.socket == null) {
            try {
                this.socket = new Socket(this.host, this.port);
            } catch (Exception e) {
                e.printStackTrace();
                connected = false;
                inputHost();
                this.socket=null;
            }
        }
        //生成客户端线程
        clientThread = new ClientThread(socket);
        clientThread.start();
        return true;
    }

    /**
     * 输入服务器IP.
     */
    private void inputHost() {
        this.host = JOptionPane.showInputDialog("输入服务器IP地址");
    }

    /**
     * 向服务器发送报文.
     *
     * @param baseMessage
     * @see BaseMessage
     */
    public void sendMessage(BaseMessage baseMessage) {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(baseMessage);
            System.out.println("发送报文" + baseMessage);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ChessClient.getInstance().connect();
        ChessClient.getInstance().sendMessage(new TestMessage());
    }
}
